#include <stdio.h>
#include <stdlib.h>
#include <sys/param.h>
#include <pthread.h>
#include <unistd.h>
#include <libxml/SAX.h>
#include <string.h>
#include "config.h"
#include "dwmstatus_types.h"
#include "curl_sax.h"
#include "gweather.h"

String gweather_formated;

pthread_mutex_t gweather_exclusive = PTHREAD_MUTEX_INITIALIZER;

void set_gweather(char *my_weather) {
  pthread_mutex_lock(&gweather_exclusive);
  COPY(gweather_formated, my_weather, sizeof(gweather_formated));
  pthread_mutex_unlock(&gweather_exclusive);
}

void get_gweather(char *dest, size_t size) {
  pthread_mutex_lock(&gweather_exclusive);
  COPY(dest, gweather_formated, size);
  pthread_mutex_unlock(&gweather_exclusive);
}

void gweather_format_weather(Weather *current) {

  String buffer;

  if (current->failed)
    set_gweather(UNAVAILABLE);
  else {
    snprintf(buffer, sizeof(buffer), WEATHER_FORMAT, current->condition, current->temperature);
    set_gweather(buffer);
  }
}


void gweather_update_weather() {
  xmlSAXHandler mySaxHandler;
  Weather weather;

  memset(&weather, 0, sizeof(weather));
  gweather_set_sax_handler(&mySaxHandler);

  curl_sax_get_data(GOOGLE_WEATHER_URL, &mySaxHandler, &weather);
  gweather_format_weather(&weather);
}

void *gweather_loop(void *ptr) {
  for (;;sleep(UPDATE_WEATHER_INTERVAL)) 
    gweather_update_weather();
}


 

void gweather_sax_on_start(void *ctx,
			   const xmlChar *localname,
			   const xmlChar *prefix,
			   const xmlChar *uri,
			   const int nb_namespaces,
			   const xmlChar **namespaces,
			   int nb_attributes,
			   int nb_defaulted,
			   const xmlChar **pattributes) {
  
  Weather *weather = ctx;

  if (!strcmp(CURRENT_CONDITIONS_NODE, localname)) {
    weather->in_current_condition = true;
    weather->failed = false;
    return;
  }

  if (!strcmp(PROBLEM_CAUSED_NODE, localname)) {
    weather->failed = true;
    return;
  }

  if (weather->in_current_condition) {
    if (!strcmp(CONDITION_NODE, localname)) {
      curl_sax_get_attribute(DATA_ATTRIBUTE, weather->condition, 500, nb_attributes, pattributes);
      return;
    }

    if (!strcmp(TEMP_NODE, localname)) {
      curl_sax_get_attribute(DATA_ATTRIBUTE, weather->temperature, 500, nb_attributes, pattributes);
      return;
    }

  }
}

void gweather_sax_on_end(void *ctx, const xmlChar* localname, const xmlChar* prefix, const xmlChar *uri) {
  Weather *weather = ctx;

  if (!strcmp(CURRENT_CONDITIONS_NODE, localname))
    weather->in_current_condition = false;
}
  

void gweather_set_sax_handler(xmlSAXHandler *sax_handler) {
  memset(sax_handler, 0, sizeof(xmlSAXHandler));
  sax_handler->initialized = XML_SAX2_MAGIC;
  sax_handler->startElementNs = gweather_sax_on_start;
  sax_handler->endElementNs = gweather_sax_on_end;
}

void gweather_start() {
  
  pthread_t weather_thread;

  pthread_create(&weather_thread, NULL, gweather_loop, NULL);

}









